// 运行结果：
// -Root
// ---Child1
// -----Leaf1
// ---Child2
// -----Leaf2

// Component.java
public abstract class Component {
    protected String name;

    public Component(String name) {
        this.name = name;
    }

    public abstract void add(Component component);

    public abstract void remove(Component component);

    public abstract void display(int depth);
}
// Leaf.java
public class Leaf extends Component {

    public Leaf(String name) {
        super(name);
    }

    @Override
    public void add(Component component) {
        // Leaf节点不能添加子节点
    }

    @Override
    public void remove(Component component) {
        // Leaf节点没有子节点可以移除
    }

    @Override
    public void display(int depth) {
        System.out.println("-".repeat(depth) + name);
    }
}
// Composite.java
import java.util.ArrayList;
import java.util.List;

public class Composite extends Component {
    private List<Component> children = new ArrayList<>();

    public Composite(String name) {
        super(name);
    }

    @Override
    public void add(Component component) {
        children.add(component);
    }

    @Override
    public void remove(Component component) {
        children.remove(component);
    }

    @Override
    public void display(int depth) {
        System.out.println("-".repeat(depth) + name);
        for (Component component : children) {
            component.display(depth + 2);
        }
    }
}
// ComponentFactory.java
public interface ComponentFactory {
    Component createComponent(String name);
}

// BasicComponentFactory.java
public class BasicComponentFactory implements ComponentFactory {
    @Override
    public Component createComponent(String name) {
        // 这里可以根据name的不同来创建Leaf或Composite对象
        // 为了简单起见，我们这里统一创建Composite对象
        return new Composite(name);
    }
}
// Client.java
public class Client {
    public static void main(String[] args) {
        ComponentFactory factory = new BasicComponentFactory();

        Component root = factory.createComponent("Root");
        Component child1 = factory.createComponent("Child1");
        Component child2 = factory.createComponent("Child2");
        Component leaf1 = factory.createComponent("Leaf1");
        Component leaf2 = factory.createComponent("Leaf2");

        root.add(child1);
        root.add(child2);
        child1.add(leaf1);
        child2.add(leaf2);

        root.display(1);
    }
}